<template>
  <div class="paper-edit">
    <el-card class="paper-edit-card">
      <template #header>
        <div class="card-header">
          <span>编辑试卷 - {{ paperForm.name }}</span>
          <div class="header-actions">
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <!-- 试卷基本信息编辑表单 -->
      <el-form :model="paperForm" :rules="paperRules" ref="paperFormRef" label-width="100px" class="paper-info-form">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="paperForm.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="总时长" prop="totalDuration">
          <el-input-number v-model="paperForm.totalDuration" :min="1" :max="300" placeholder="请输入总时长(分钟)" />
          <span class="unit">分钟</span>
        </el-form-item>
        <el-form-item label="总题数" prop="totalQuestions">
          <el-input-number v-model="paperForm.totalQuestions" :min="1" :max="500" placeholder="请输入总题数" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="savePaperInfo">保存基本信息</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 统一操作按钮区域 -->
      <div class="paper-actions">
        <el-dropdown @command="handleAddQuestion">
          <el-button type="primary">
            添加题目<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="politics">政治理论</el-dropdown-item>
              <el-dropdown-item command="commonSense">常识判断</el-dropdown-item>
              <el-dropdown-item command="language">言语理解与表达</el-dropdown-item>
              <el-dropdown-item command="quantity">数量关系</el-dropdown-item>
              <el-dropdown-item command="judgment">判断推理</el-dropdown-item>
              <el-dropdown-item command="dataAnalysis">资料分析</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" @click="showManualImportDialog = true">手动批量导入</el-button>
        <el-button 
          type="danger" 
          @click="executeBatchDelete" 
          :loading="clearingQuestions"
        >
          批量删除
        </el-button>
      </div>
      
      <!-- 题目总数显示 -->
      <div class="total-questions-display">
        题目总数: {{ totalQuestionsCount }}
      </div>
      
      <el-tabs v-model="activeModuleTab">
        <el-tab-pane label="政治理论" name="politics">
          <PaperQuestionManager 
            :questions="paperQuestions.politics" 
            :paper-id="currentPaperId"
            :editable="true"
            :show-batch-delete="showBatchDelete"
            :selected-questions="selectedQuestions.politics"
            :show-add-question-dialog="showAddQuestionDialog.politics"
            @add-question="(question) => addQuestionDirect('politics', question)"
            @remove-question="(questionId) => removeQuestion('politics', questionId)"
            @update-question="(question) => updateQuestionDirect('politics', question)"
            @questions-updated="onQuestionsUpdated"
            @toggle-question-selection="(questionId, selected) => toggleQuestionSelection('politics', questionId, selected)"
            @toggle-select-all="(selected) => toggleSelectAll('politics', selected)"
          />
        </el-tab-pane>
        <el-tab-pane label="常识判断" name="commonSense">
          <PaperQuestionManager 
            :questions="paperQuestions.commonSense" 
            :paper-id="currentPaperId"
            :editable="true"
            :show-batch-delete="showBatchDelete"
            :selected-questions="selectedQuestions.commonSense"
            :show-add-question-dialog="showAddQuestionDialog.commonSense"
            @add-question="(question) => addQuestionDirect('commonSense', question)"
            @remove-question="(questionId) => removeQuestion('commonSense', questionId)"
            @update-question="(question) => updateQuestionDirect('commonSense', question)"
            @questions-updated="onQuestionsUpdated"
            @toggle-question-selection="(questionId, selected) => toggleQuestionSelection('commonSense', questionId, selected)"
            @toggle-select-all="(selected) => toggleSelectAll('commonSense', selected)"
          />
        </el-tab-pane>
        <el-tab-pane label="言语理解与表达" name="language">
          <PaperQuestionManager 
            :questions="paperQuestions.language" 
            :paper-id="currentPaperId"
            :editable="true"
            :show-batch-delete="showBatchDelete"
            :selected-questions="selectedQuestions.language"
            :show-add-question-dialog="showAddQuestionDialog.language"
            @add-question="(question) => addQuestionDirect('language', question)"
            @remove-question="(questionId) => removeQuestion('language', questionId)"
            @update-question="(question) => updateQuestionDirect('language', question)"
            @questions-updated="onQuestionsUpdated"
            @toggle-question-selection="(questionId, selected) => toggleQuestionSelection('language', questionId, selected)"
            @toggle-select-all="(selected) => toggleSelectAll('language', selected)"
          />
        </el-tab-pane>
        <el-tab-pane label="数量关系" name="quantity">
          <PaperQuestionManager 
            :questions="paperQuestions.quantity" 
            :paper-id="currentPaperId"
            :editable="true"
            :show-batch-delete="showBatchDelete"
            :selected-questions="selectedQuestions.quantity"
            :show-add-question-dialog="showAddQuestionDialog.quantity"
            @add-question="(question) => addQuestionDirect('quantity', question)"
            @remove-question="(questionId) => removeQuestion('quantity', questionId)"
            @update-question="(question) => updateQuestionDirect('quantity', question)"
            @questions-updated="onQuestionsUpdated"
            @toggle-question-selection="(questionId, selected) => toggleQuestionSelection('quantity', questionId, selected)"
            @toggle-select-all="(selected) => toggleSelectAll('quantity', selected)"
          />
        </el-tab-pane>
        <el-tab-pane label="判断推理" name="judgment">
          <PaperQuestionManager 
            :questions="paperQuestions.judgment" 
            :paper-id="currentPaperId"
            :editable="true"
            :show-batch-delete="showBatchDelete"
            :selected-questions="selectedQuestions.judgment"
            :show-add-question-dialog="showAddQuestionDialog.judgment"
            @add-question="(question) => addQuestionDirect('judgment', question)"
            @remove-question="(questionId) => removeQuestion('judgment', questionId)"
            @update-question="(question) => updateQuestionDirect('judgment', question)"
            @questions-updated="onQuestionsUpdated"
            @toggle-question-selection="(questionId, selected) => toggleQuestionSelection('judgment', questionId, selected)"
            @toggle-select-all="(selected) => toggleSelectAll('judgment', selected)"
          />
        </el-tab-pane>
        <el-tab-pane label="资料分析" name="dataAnalysis">
          <PaperQuestionManager 
            :questions="paperQuestions.dataAnalysis" 
            :paper-id="currentPaperId"
            :editable="true"
            :show-batch-delete="showBatchDelete"
            :selected-questions="selectedQuestions.dataAnalysis"
            :show-add-question-dialog="showAddQuestionDialog.dataAnalysis"
            @add-question="(question) => addQuestionDirect('dataAnalysis', question)"
            @remove-question="(questionId) => removeQuestion('dataAnalysis', questionId)"
            @update-question="(question) => updateQuestionDirect('dataAnalysis', question)"
            @questions-updated="onQuestionsUpdated"
            @toggle-question-selection="(questionId, selected) => toggleQuestionSelection('dataAnalysis', questionId, selected)"
            @toggle-select-all="(selected) => toggleSelectAll('dataAnalysis', selected)"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 手动批量导入对话框 -->
    <el-dialog v-model="showManualImportDialog" title="手动批量导入题目" width="800px">
      <el-form :model="manualImportForm" label-width="100px">
        <el-form-item label="题目内容">
          <el-input
            v-model="manualImportForm.content"
            type="textarea"
            :rows="10"
            placeholder="请粘贴题目内容，格式如下：&#10;1．题目内容&#10;&#10;选项：&#10;A. 选项A&#10;B. 选项B&#10;C. 选项C&#10;D. 选项D&#10;&#10;正确答案：A&#10;解析：解析内容"
            @input="validateQuestionsRealTime"
          />
        </el-form-item>
      </el-form>
      
      <div class="manual-import-actions">
        <el-button @click="resetManualImport">重置</el-button>
      </div>
      
      <!-- 验证结果展示 -->
      <div v-if="validationResult.show" class="validation-result" :class="validationResult.type">
        <h4>{{ validationResult.title }}</h4>
        <p>{{ validationResult.message }}</p>
        <div v-if="validationResult.details && validationResult.details.length > 0">
          <h5>详细信息：</h5>
          <ul>
            <li v-for="(detail, index) in validationResult.details" :key="index">
              {{ detail }}
            </li>
          </ul>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showManualImportDialog = false">取消</el-button>
          <el-button type="primary" @click="handleManualImport" :disabled="!validationResult.valid">导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PaperQuestionManager from '@/components/PaperQuestionManager.vue'
import * as paperApi from '@/api/paper'
import * as politicsApi from '@/api/politics'
import * as commonSenseApi from '@/api/commonsense'
import * as languageApi from '@/api/language'
import * as quantityApi from '@/api/quantity'
import * as judgmentApi from '@/api/judgment'
import * as dataAnalysisApi from '@/api/dataAnalysis'

// 路由相关
const route = useRoute()
const router = useRouter()

// 试卷表单数据
const paperForm = reactive({
  id: 0,
  name: '',
  totalDuration: 120,
  totalQuestions: 100
})

// 手动导入表单数据
const manualImportForm = reactive({
  content: ''
})

// 验证结果
const validationResult = reactive({
  show: false,
  valid: false,
  type: '', // 'success' 或 'error'
  title: '',
  message: '',
  details: [] as string[]
})

// 防抖定时器
let validateTimer: number | null = null

// 试卷表单验证规则
const paperRules = {
  name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  totalDuration: [{ required: true, message: '请输入总时长', trigger: 'blur' }],
  totalQuestions: [{ required: true, message: '请输入总题数', trigger: 'blur' }]
}

// 当前试卷ID
const currentPaperId = ref(0)

// 激活的模块标签页
const activeModuleTab = ref('politics')

// 各模块题目
const paperQuestions = reactive({
  politics: [] as any[],
  commonSense: [] as any[],
  language: [] as any[],
  quantity: [] as any[],
  judgment: [] as any[],
  dataAnalysis: [] as any[]
})

// 计算题目总数
const totalQuestionsCount = computed(() => {
  return (
    paperQuestions.politics.length +
    paperQuestions.commonSense.length +
    paperQuestions.language.length +
    paperQuestions.quantity.length +
    paperQuestions.judgment.length +
    paperQuestions.dataAnalysis.length
  );
});

// 批量删除相关状态
const showBatchDelete = ref(true) // 默认保持选择题目的状态
const clearingQuestions = ref(false)
const selectedQuestions = reactive({
  politics: [] as number[],
  commonSense: [] as number[],
  language: [] as number[],
  quantity: [] as number[],
  judgment: [] as number[],
  dataAnalysis: [] as number[]
})

// 添加题目对话框控制状态
const showAddQuestionDialog = reactive({
  politics: false,
  commonSense: false,
  language: false,
  quantity: false,
  judgment: false,
  dataAnalysis: false
});

// 对话框控制
const showManualImportDialog = ref(false)

// 表单引用
const paperFormRef = ref()

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取试卷详情
const fetchPaperDetail = async () => {
  const paperId = Number(route.params.id)
  if (!paperId) {
    ElMessage.error('试卷ID无效')
    router.back()
    return
  }
  
  currentPaperId.value = paperId
  
  try {
    // 获取试卷基本信息
    const paperRes: any = await paperApi.getPaperById(paperId)
    if (paperRes.code === 200) {
      paperForm.id = paperRes.data.id
      paperForm.name = paperRes.data.name
      paperForm.totalDuration = paperRes.data.totalDuration
      paperForm.totalQuestions = paperRes.data.totalQuestions
    } else {
      ElMessage.error(paperRes.message || '获取试卷信息失败')
      router.back()
      return
    }
    
    // 获取试卷题目数据
    await fetchPaperQuestions(paperId)
  } catch (error) {
    console.error('获取试卷详情失败:', error)
    ElMessage.error('获取试卷详情失败')
    router.back()
  }
}

// 获取试卷题目
const fetchPaperQuestions = async (paperId: number) => {
  try {
    console.log('开始获取试卷题目，试卷ID:', paperId);
    const res: any = await paperApi.getPaperQuestions(paperId)
    console.log('获取试卷题目返回结果:', res);
    if (res.code === 200) {
      console.log('获取到的题目数据:', res.data);
      
      // 处理政治理论模块
      paperQuestions.politics = (res.data?.politics || []).map((question: any) => {
        console.log('政治理论题目:', question);
        // 解析选项数据
        let options: any[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理常识判断模块
      paperQuestions.commonSense = (res.data?.commonSense || []).map((question: any) => {
        console.log('常识判断题目:', question);
        // 解析选项数据
        let options: any[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理言语理解与表达模块
      paperQuestions.language = (res.data?.language || []).map((question: any) => {
        console.log('言语理解题目:', question);
        // 解析选项数据
        let options: any[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理数量关系模块
      paperQuestions.quantity = (res.data?.quantity || []).map((question: any) => {
        console.log('数量关系题目:', question);
        // 解析选项数据
        let options: any[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理判断推理模块
      paperQuestions.judgment = (res.data?.judgment || []).map((question: any) => {
        console.log('判断推理题目:', question);
        // 解析选项数据
        let options: any[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理资料分析模块
      paperQuestions.dataAnalysis = (res.data?.dataAnalysis || []).map((question: any) => {
        console.log('资料分析题目:', question);
        // 解析选项数据
        let options: any[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      console.log('各模块题目数量:');
      console.log('政治理论:', paperQuestions.politics.length);
      console.log('常识判断:', paperQuestions.commonSense.length);
      console.log('言语理解与表达:', paperQuestions.language.length);
      console.log('数量关系:', paperQuestions.quantity.length);
      console.log('判断推理:', paperQuestions.judgment.length);
      console.log('资料分析:', paperQuestions.dataAnalysis.length);
    } else {
      ElMessage.error(res.message || '获取试卷题目失败')
    }
  } catch (error) {
    console.error('获取试卷题目失败:', error)
    ElMessage.error('获取试卷题目失败')
  }
}

// 保存试卷基本信息
const savePaperInfo = async () => {
  if (!paperFormRef.value) return
  
  await paperFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const paperData = {
          ...paperForm,
          id: paperForm.id || undefined
        }
        
        // 编辑试卷
        const res: any = await paperApi.updatePaper(paperData)
        
        if (res.code === 200) {
          ElMessage.success('试卷信息更新成功')
        } else {
          ElMessage.error(res.message || '试卷信息更新失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 重置手动导入
const resetManualImport = () => {
  manualImportForm.content = '';
  validationResult.show = false;
  validationResult.valid = false;
  validationResult.type = '';
  validationResult.title = '';
  validationResult.message = '';
  validationResult.details = [];
}

// 实时格式验证（防抖）
const validateQuestionsRealTime = () => {
  // 清除之前的定时器
  if (validateTimer) {
    clearTimeout(validateTimer);
  }
  
  // 设置新的定时器，延迟500ms执行验证
  validateTimer = setTimeout(() => {
    if (!manualImportForm.content.trim()) {
      validationResult.show = false;
      validationResult.valid = false;
      return;
    }
    
    try {
      // 解析题目内容
      const questions = parseQuestions(manualImportForm.content);
      
      if (questions.length === 0) {
        validationResult.show = true;
        validationResult.valid = false;
        validationResult.type = 'error';
        validationResult.title = '验证失败';
        validationResult.message = '未解析到有效题目，请检查题目格式';
        validationResult.details = [];
        return;
      }
      
      // 验证每道题目的完整性（只验证必要字段）
      const validationDetails = [];
      let valid = true;
      
      for (let i = 0; i < questions.length; i++) {
        const question = questions[i];
        const questionNum = i + 1;
        
        if (!question.content || !question.content.trim()) {
          validationDetails.push(`第${questionNum}题：题目内容为空`);
          valid = false;
        }
        
        // 只验证选项数量，不强制要求正确答案和解析
        if (question.options && question.options.length > 0) {
          // 选择题验证
          if (question.options.length < 2) {
            validationDetails.push(`第${questionNum}题：选择题选项少于2个`);
            valid = false;
          }
          
          // 如果提供了正确答案，则验证其有效性
          if (question.correctAnswer && question.correctAnswer.trim()) {
            // 验证答案是否在选项范围内
            const validAnswers = question.options.map((opt: any, idx: number) => 
              String.fromCharCode(65 + idx)).join('');
            if (!validAnswers.includes(question.correctAnswer.toUpperCase())) {
              validationDetails.push(`第${questionNum}题：正确答案"${question.correctAnswer}"不在选项范围内`);
              valid = false;
            }
          }
        }
      }
      
      validationResult.show = true;
      validationResult.valid = valid;
      validationResult.type = valid ? 'success' : 'error';
      validationResult.title = valid ? '验证通过' : '验证失败';
      validationResult.message = valid 
        ? `格式验证通过，共解析到${questions.length}道题目` 
        : `格式验证失败，存在${validationDetails.length}个问题`;
      validationResult.details = validationDetails;
    } catch (error: any) {
      console.error('验证失败:', error);
      validationResult.show = true;
      validationResult.valid = false;
      validationResult.type = 'error';
      validationResult.title = '验证失败';
      validationResult.message = '题目格式错误，请检查后重试';
      validationResult.details = [error.message || '未知错误'];
    }
  }, 500);
}

// 解析题目内容
const parseQuestions = (content: string) => {
  const questions = [];
  // 按题目分割（以数字开头的题目）
  const questionBlocks = content.split(/\n\d+[\uFF0E\.．]/).filter(block => block.trim());
  
  for (let i = 0; i < questionBlocks.length; i++) {
    const block = questionBlocks[i];
    if (!block.trim()) continue;
    
    let contentStr = '';
    const options: { content: string }[] = [];
    let correctAnswer = '';
    let analysis = '';
    
    // 按行分割处理
    const lines = block.split('\n');
    
    // 查找选项开始位置
    let optionStartIndex = -1;
    for (let j = 0; j < lines.length; j++) {
      const trimmedLine = lines[j].trim();
      if (trimmedLine.match(/^[A-D](\.|．)/)) {
        optionStartIndex = j;
        break;
      }
    }
    
    // 查找答案和解析位置
    let answerLineIndex = -1;
    let analysisLineIndex = -1;
    for (let j = 0; j < lines.length; j++) {
      const trimmedLine = lines[j].trim();
      if (trimmedLine.startsWith('正确答案：')) {
        answerLineIndex = j;
      } else if (trimmedLine.startsWith('解析：')) {
        analysisLineIndex = j;
      }
    }
    
    if (optionStartIndex >= 0) {
      // 有选项的题目
      contentStr = lines.slice(0, optionStartIndex).join('\n').trim();
      
      // 解析选项
      const optionsMap: Record<string, string> = {};
      for (let j = optionStartIndex; j < lines.length; j++) {
        // 遇到答案或解析行时停止
        if (j === answerLineIndex || j === analysisLineIndex) {
          break;
        }
        
        const trimmedLine = lines[j].trim();
        const optionMatch = trimmedLine.match(/^([A-D])(\.|．)\s*(.*)/);
        if (optionMatch) {
          optionsMap[optionMatch[1]] = optionMatch[3].trim();
        }
      }
      
      // 按顺序添加选项
      const optionKeys = ['A', 'B', 'C', 'D'];
      for (const key of optionKeys) {
        if (optionsMap[key]) {
          options.push({ content: optionsMap[key] });
        }
      }
    } else {
      // 没有选项的题目
      let endIndex = lines.length;
      if (answerLineIndex >= 0) {
        endIndex = answerLineIndex;
      } else if (analysisLineIndex >= 0) {
        endIndex = analysisLineIndex;
      }
      contentStr = lines.slice(0, endIndex).join('\n').trim();
    }
    
    // 提取答案
    if (answerLineIndex >= 0) {
      const answerMatch = lines[answerLineIndex].match(/正确答案：\s*([A-Da-dA-D])/);
      correctAnswer = answerMatch ? answerMatch[1].toUpperCase() : '';
    }
    
    // 提取解析
    if (analysisLineIndex >= 0) {
      analysis = lines.slice(analysisLineIndex + 1).join('\n').trim();
    }
    
    questions.push({
      content: contentStr,
      options,
      correctAnswer,
      analysis,
      type: options.length > 0 ? 'single_choice' : 'true_false'
    });
  }
  
  return questions;
}

// 手动批量导入题目
const handleManualImport = async () => {
  if (!manualImportForm.content.trim()) {
    ElMessage.warning('请输入题目内容');
    return;
  }
  
  try {
    // 解析题目内容
    const questions = parseQuestions(manualImportForm.content);
    
    // 清空输入框
    manualImportForm.content = '';
    showManualImportDialog.value = false;
    
    // 直接保存新导入的题目到数据库
    await saveNewQuestions(questions, activeModuleTab.value);
    
    ElMessage.success(`题目已添加到${activeModuleTab.value}模块，试卷题目保存成功，成功导入并保存 ${questions.length} 道题目`);
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('题目格式错误，请检查后重试');
  }
}

// 保存新导入的题目
const saveNewQuestions = async (newQuestions: any[], module: string) => {
  try {
    // 获取对应的API模块
    const moduleApis = {
      politics: politicsApi,
      commonSense: commonSenseApi,
      language: languageApi,
      quantity: quantityApi,
      judgment: judgmentApi,
      dataAnalysis: dataAnalysisApi
    };
    
    const api = moduleApis[module as keyof typeof moduleApis];
    
    // 先将新题目添加到本地列表中（临时状态，没有ID）
    const tempQuestions: any[] = [];
    newQuestions.forEach(question => {
      const tempQuestion = { ...question, tempId: Date.now() + Math.random() };
      paperQuestions[module as keyof typeof paperQuestions].push(tempQuestion);
      tempQuestions.push(tempQuestion);
    });
    
    // 保存新题目到对应的题目表中
    const savedQuestions = [];
    for (let i = 0; i < newQuestions.length; i++) {
      const question = newQuestions[i];
      const tempQuestion = tempQuestions[i];
      
      try {
        // 构造题目数据
        // 修复选项和正确答案的存储格式，使其保持一致
        let optionsData = '';
        if (question.options && question.options.length > 0) {
          // 将选项数组转换为对象格式 {A: "选项A内容", B: "选项B内容", ...}
          const optionsObj: Record<string, string> = {};
          question.options.forEach((option: any, index: number) => {
            const optionLabel = String.fromCharCode(65 + index); // A, B, C, D
            optionsObj[optionLabel] = option.content || option;
          });
          optionsData = JSON.stringify(optionsObj);
        }
        
        const questionData = {
          questionType: question.type === 'single' ? 'single_choice' : 
                       question.type === 'multiple' ? 'multiple_choice' :
                       question.type === 'trueFalse' ? 'true_false' :
                       question.type === 'fillBlank' ? 'fill_blank' : question.type,
          content: question.content,
          options: optionsData,
          correctAnswer: question.correctAnswer || (question.correctAnswers ? JSON.stringify(question.correctAnswers) : ''),
          explanation: question.analysis || ''
        };
        
        // 创建新题目
        const res: any = await api.addQuestion(questionData);
        if (res.code === 200) {
          // 修复：正确处理question_id字段，使用res.data.questionId
          const savedQuestion = { ...question, id: res.data.questionId || res.data.id };
          savedQuestions.push({
            module: module,
            question: savedQuestion,
            tempQuestion: tempQuestion
          });
        } else {
          ElMessage.error(`添加${module}模块题目失败: ${res.message}`);
        }
      } catch (error) {
        console.error(`保存${module}模块题目失败:`, error);
        ElMessage.error(`保存${module}模块题目失败`);
      }
    }
    
    // 构造试卷题目关联数据
    const paperQuestionsData = [];
    let order = 1;
    for (const item of savedQuestions) {
      const { module, question } = item;
      paperQuestionsData.push({
        paperId: currentPaperId.value,
        questionId: question.id,
        questionType: module,
        questionOrder: order++
      });
    }
    
    // 如果没有题目，不需要保存
    if (paperQuestionsData.length === 0) {
      ElMessage.info('没有题目需要保存');
      return;
    }
    
    // 调用API添加题目关联到数据库
    const res: any = await paperApi.addQuestionsToPaper(currentPaperId.value, paperQuestionsData);
    if (res.code === 200) {
      // 移除了单独的试卷题目保存成功提示，整合到导入成功提示中
      
      // 更新本地题目数据
      for (const item of savedQuestions) {
        const { module, question, tempQuestion } = item;
        const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
        // 查找对应的临时题目索引
        const index = moduleQuestions.findIndex((q: any) => q.tempId === tempQuestion.tempId);
        if (index !== -1) {
          // 更新题目数据，包括ID
          moduleQuestions[index] = question;
        } else {
          // 如果没找到临时题目，添加新的题目
          moduleQuestions.push(question);
        }
      }
      
      ElMessage.success(`${newQuestions.length}道题目已成功保存`);
    } else {
      ElMessage.error(res.message || '试卷题目保存失败');
      
      // 如果保存失败，移除临时添加的题目
      for (const tempQuestion of tempQuestions) {
        const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
        const index = moduleQuestions.findIndex((q: any) => q.tempId === tempQuestion.tempId);
        if (index !== -1) {
          moduleQuestions.splice(index, 1);
        }
      }
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('试卷题目保存失败');
  }
}

// 直接添加题目并保存到数据库
const addQuestionDirect = async (module: string, question: any) => {
  try {
    // 获取对应的API模块
    const moduleApis = {
      politics: politicsApi,
      commonSense: commonSenseApi,
      language: languageApi,
      quantity: quantityApi,
      judgment: judgmentApi,
      dataAnalysis: dataAnalysisApi
    };
    
    const api = moduleApis[module as keyof typeof moduleApis];
    
    // 构造题目数据
    let optionsData = '';
    if (question.options && question.options.length > 0) {
      // 将选项数组转换为对象格式 {A: "选项A内容", B: "选项B内容", ...}
      const optionsObj: Record<string, string> = {};
      question.options.forEach((option: any, index: number) => {
        const optionLabel = String.fromCharCode(65 + index); // A, B, C, D
        optionsObj[optionLabel] = option.content || option;
      });
      optionsData = JSON.stringify(optionsObj);
    }
    
    const questionData = {
      questionType: question.type === 'single' ? 'single_choice' : 
                   question.type === 'multiple' ? 'multiple_choice' :
                   question.type === 'trueFalse' ? 'true_false' :
                   question.type === 'fillBlank' ? 'fill_blank' : question.type,
      content: question.content,
      options: optionsData,
      correctAnswer: question.correctAnswer || (question.correctAnswers ? JSON.stringify(question.correctAnswers) : ''),
      explanation: question.analysis || ''
    };
    
    // 创建新题目
    const res: any = await api.addQuestion(questionData);
    if (res.code === 200) {
      // 获取保存后的题目ID
      const savedQuestion = { ...question, id: res.data.questionId || res.data.id };
      
      // 添加到本地列表
      paperQuestions[module as keyof typeof paperQuestions].push(savedQuestion);
      
      // 构造试卷题目关联数据
      const paperQuestionData = {
        paperId: currentPaperId.value,
        questionId: savedQuestion.id,
        questionType: module,
        questionOrder: paperQuestions[module as keyof typeof paperQuestions].length
      };
      
      // 添加题目关联到试卷
      await paperApi.addQuestionsToPaper(currentPaperId.value, [paperQuestionData]);
      
      ElMessage.success('题目添加成功');
      return savedQuestion;
    } else {
      ElMessage.error(`添加${module}模块题目失败: ${res.message}`);
      return null;
    }
  } catch (error) {
    console.error(`保存${module}模块题目失败:`, error);
    ElMessage.error(`保存${module}模块题目失败`);
    return null;
  }
}

// 直接更新题目并保存到数据库
const updateQuestionDirect = async (module: string, question: any) => {
  try {
    // 获取对应的API模块
    const moduleApis = {
      politics: politicsApi,
      commonSense: commonSenseApi,
      language: languageApi,
      quantity: quantityApi,
      judgment: judgmentApi,
      dataAnalysis: dataAnalysisApi
    };
    
    const api = moduleApis[module as keyof typeof moduleApis];
    
    // 构造题目数据
    let optionsData = '';
    if (question.options && question.options.length > 0) {
      // 将选项数组转换为对象格式 {A: "选项A内容", B: "选项B内容", ...}
      const optionsObj: Record<string, string> = {};
      question.options.forEach((option: any, index: number) => {
        const optionLabel = String.fromCharCode(65 + index); // A, B, C, D
        optionsObj[optionLabel] = option.content || option;
      });
      optionsData = JSON.stringify(optionsObj);
    }
    
    const questionData = {
      questionType: question.type === 'single' ? 'single_choice' : 
                   question.type === 'multiple' ? 'multiple_choice' :
                   question.type === 'trueFalse' ? 'true_false' :
                   question.type === 'fillBlank' ? 'fill_blank' : question.type,
      content: question.content,
      options: optionsData,
      correctAnswer: question.correctAnswer || (question.correctAnswers ? JSON.stringify(question.correctAnswers) : ''),
      explanation: question.analysis || ''
    };
    
    // 更新题目
    if (question.id && typeof question.id === 'number') {
      const res: any = await api.updateQuestion(question.id.toString(), questionData);
      if (res.code === 200) {
        // 更新本地题目数据
        const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
        const index = moduleQuestions.findIndex((q: any) => q.id === question.id);
        if (index !== -1) {
          moduleQuestions[index] = { ...moduleQuestions[index], ...question };
        }
        
        // ElMessage.success(`题目已在${module}模块中更新`);
      } else {
        ElMessage.error(`更新${module}模块题目失败: ${res.message}`);
      }
    } else {
      ElMessage.error(`题目ID无效，无法更新`);
      return null;
    }
  } catch (error) {
    console.error(`更新${module}模块题目失败:`, error);
    ElMessage.error(`更新${module}模块题目失败`);
    return null;
  }
}

// 移除题目
const removeQuestion = async (module: string, questionId: number) => {
  // 实现移除题目逻辑
  const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
  const index = moduleQuestions.findIndex((q: any) => q.id === questionId);
  if (index !== -1) {
    // 如果题目已经有ID，直接从数据库中删除
    if (questionId && typeof questionId === 'number') {
      try {
        // 获取对应的API模块
        const moduleApis = {
          politics: politicsApi,
          commonSense: commonSenseApi,
          language: languageApi,
          quantity: quantityApi,
          judgment: judgmentApi,
          dataAnalysis: dataAnalysisApi
        };
        
        const api = moduleApis[module as keyof typeof moduleApis];
        
        // 从数据库中删除题目
        const res: any = await api.deleteQuestion(questionId.toString());
        if (res.code === 200) {
          // 从试卷中移除题目关联
          await paperApi.removeQuestionFromPaper(currentPaperId.value, questionId);
          
          // 从本地数组中移除
          moduleQuestions.splice(index, 1);
          
          ElMessage.success(`题目已从${module}模块中删除`);
        } else {
          ElMessage.error(res.message || '删除题目失败');
        }
      } catch (error: any) {
        console.error('删除题目失败:', error);
        ElMessage.error(error.message || '删除题目失败');
      }
    } else {
      // 如果题目没有ID，直接从本地数组中移除
      moduleQuestions.splice(index, 1);
      ElMessage.success(`题目已从${module}模块中移除`);
    }
  }
}

// 切换题目选择状态
const toggleQuestionSelection = (module: string, questionId: number, selected: boolean) => {
  const moduleSelectedQuestions = selectedQuestions[module as keyof typeof selectedQuestions];
  const index = moduleSelectedQuestions.indexOf(questionId);
  
  if (selected && index === -1) {
    // 选中题目
    moduleSelectedQuestions.push(questionId);
  } else if (!selected && index !== -1) {
    // 取消选中题目
    moduleSelectedQuestions.splice(index, 1);
  }
}

// 全选/取消全选
const toggleSelectAll = (module: string, selected: boolean) => {
  const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
  const moduleSelectedQuestions = selectedQuestions[module as keyof typeof selectedQuestions];
  
  if (selected) {
    // 全选
    moduleQuestions.forEach(question => {
      if (!moduleSelectedQuestions.includes(question.id)) {
        moduleSelectedQuestions.push(question.id);
      }
    });
  } else {
    // 取消全选
    selectedQuestions[module as keyof typeof selectedQuestions] = [];
  }
}

// 执行批量删除
const executeBatchDelete = async () => {
  // 收集所有选中的题目
  const allSelectedQuestions: { moduleId: number; moduleType: string }[] = [];
  
  Object.keys(selectedQuestions).forEach(module => {
    const questions = selectedQuestions[module as keyof typeof selectedQuestions];
    questions.forEach(questionId => {
      allSelectedQuestions.push({
        moduleId: questionId,
        moduleType: module
      });
    });
  });
  
  if (allSelectedQuestions.length === 0) {
    ElMessage.info('请先选择要删除的题目');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${allSelectedQuestions.length} 道题目吗？这将从题库中永久删除这些题目。`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      clearingQuestions.value = true;
      
      // 获取各模块的API
      const moduleApis = {
        politics: politicsApi,
        commonSense: commonSenseApi,
        language: languageApi,
        quantity: quantityApi,
        judgment: judgmentApi,
        dataAnalysis: dataAnalysisApi
      };
      
      // 记录删除成功的题目数量
      let successCount = 0;
      
      // 逐个删除题目
      for (const item of allSelectedQuestions) {
        try {
          const api = moduleApis[item.moduleType as keyof typeof moduleApis];
          const res: any = await api.deleteQuestion(item.moduleId.toString());
          
          if (res.code === 200) {
            successCount++;
            // 从试卷中移除题目关联
            await paperApi.removeQuestionFromPaper(currentPaperId.value, item.moduleId);
            
            // 从本地数组中移除
            const moduleQuestions = paperQuestions[item.moduleType as keyof typeof paperQuestions];
            const index = moduleQuestions.findIndex((q: any) => q.id === item.moduleId);
            if (index !== -1) {
              moduleQuestions.splice(index, 1);
            }
          } else {
            console.error(`删除${item.moduleType}模块题目失败:`, res.message);
          }
        } catch (error) {
          console.error(`删除${item.moduleType}模块题目异常:`, error);
        }
      }
      
      // 清空选中的题目
      Object.keys(selectedQuestions).forEach(key => {
        selectedQuestions[key as keyof typeof selectedQuestions] = [];
      });
      
      ElMessage.success(`成功删除 ${successCount} 道题目`);
    } catch (error) {
      console.error('批量删除题目失败:', error);
      ElMessage.error('批量删除题目失败');
    } finally {
      clearingQuestions.value = false;
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 处理添加题目按钮点击事件
const handleAddQuestion = (module: string) => {
  // 设置当前激活的模块标签页
  activeModuleTab.value = module;
  
  // 触发对应模块的添加题目对话框
  showAddQuestionDialog[module as keyof typeof showAddQuestionDialog] = true;
  
  // 在下一个tick重置状态，确保对话框能正确显示
  nextTick(() => {
    showAddQuestionDialog[module as keyof typeof showAddQuestionDialog] = false;
  });
};

// 题目更新处理
const onQuestionsUpdated = () => {
  // 只在用户明确点击保存按钮时才保存，不在题目更新时自动保存
  // 这样可以避免查看试卷时误操作
}

// 组件挂载时获取试卷详情
onMounted(() => {
  fetchPaperDetail()
})
</script>

<style scoped>
.paper-edit {
  padding: 20px;
}

.paper-edit-card {
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paper-info-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.paper-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  margin: 0 0 20px 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.paper-actions .el-button {
  margin-left: 0;
}

.total-questions-display {
  margin: 10px 0;
  padding: 8px 12px;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  font-size: 16px;
  font-weight: bold;
  color: #67c23a;
  text-align: center;
}

.manual-import-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.validation-result {
  margin-top: 20px;
  padding: 10px;
  border-radius: 4px;
}

.validation-result.success {
  background-color: #e1f3d8;
  border: 1px solid #c2e7b0;
  color: #74be2e;
}

.validation-result.error {
  background-color: #fde2e2;
  border: 1px solid #f56c6c;
  color: #f56c6c;
}

.validation-result h4 {
  margin: 0;
  font-size: 16px;
}

.validation-result p {
  margin: 5px 0 0;
  font-size: 14px;
}

.validation-result ul {
  margin: 10px 0 0;
  padding-left: 20px;
  list-style-type: disc;
}

.validation-result li {
  margin: 5px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.dialog-footer .el-button {
  margin-left: 0;
}
</style>